import time
import json
import requests
import random
from openpyxl import Workbook, load_workbook
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.microsoft import EdgeChromiumDriverManager


requests.packages.urllib3.disable_warnings()

# 加载用户数据
def user_data_list_parse():
    user_data_list = []
    book = load_workbook('账户.xlsx')
    sheet = book.active
    col_data = tuple(sheet.columns)
    
    if(len(col_data[0]) != len(col_data[1])):
        print('账户个数和密码个数不符合，请检查后运行！')
        exit(0)

    for i in range(len(col_data[0])):
        user_data_list.append([col_data[0][i].value, col_data[1][i].value])

    return user_data_list
    


# 滑动条事件
def slide_solution(driver):
    try:
        slide_btn = driver.find_element(by=By.XPATH, value='//*[@id="nc_1_n1z"]')
        # 按住滑块按钮
        ActionChains(driver).click_and_hold(slide_btn).perform()
        # 模拟缓慢的滑动
        i = 0
        while i <= 420:  
            time.sleep(0.1)
            ActionChains(driver).move_by_offset(20,0).perform()
            i += 30
        # 释放鼠标
        ActionChains(driver).release().perform()
        time.sleep(1)
    except:
        return 0
    


# 随机选择并构建题目列表
def random_list():
    ran = random.sample(range(0, 39),20)
    question_list = []
    for i in ran:
        t = question_data[i].split('-')
        question_list.append({"questionId": t[0],"questionContent": t[1]})

    return question_list


#模拟登录的事件
def login(user_data):
    # 点击登录按钮
    WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.XPATH, '/html/body/div/div/div[1]/div/header/div/div[2]/div[2]/div/span/a')))
    el = driver.find_element(By.XPATH,'/html/body/div/div/div[1]/div/header/div/div[2]/div[2]/div/span/a')
    el.click()
    time.sleep(2)

    # account
    el = driver.find_element(By.XPATH,'//*[@id="account"]')
    el.send_keys(user_data[0])
    time.sleep(0.5)

    # password
    el = driver.find_element(By.XPATH,'//*[@id="password"]')
    el.send_keys(user_data[1])
    time.sleep(0.5)

    # 登录
    el = driver.find_element(By.CSS_SELECTOR,"[type='submit']")
    el.click()
    time.sleep(2)
    # 如果有滑动条的话
    slide_solution(driver)

    
    #cookie和数据
    cookie = ''
    cookies=driver.get_cookies()
    for i in cookies:
        cookie = cookie + i['name'] + '=' + i['value'] + ';'
    reqtoken = driver.execute_script('return window.__DATA__.reqtoken')

    
    yi_jian_man_fen(cookie,reqtoken,user_data[0])

    #点击退出
    el = driver.find_element(By.XPATH,'//*[@id="app"]/div/div[1]/div/header/div/div[2]/div[2]/div/a')
    el.click()
    time.sleep(1)
    el = driver.find_element(By.XPATH,'//*[@id="app"]/div/div[1]/div/header/div/div[2]/div[2]/div/div/ul/li[6]/a')
    driver.execute_script('arguments[0].click()', el)
    time.sleep(1)


#开始答题
def yi_jian_man_fen(cookie,reqtoken,account):
    print(account+'，开始答题')
    url = 'https://www.2-class.com/api/quiz/commit'
    headers = {
        'Cookie': cookie,
        'Content-Type': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'
    }
    time = random.randint(100, 350)
    data = {
        "list": random_list(),
        "time": time,
        "reqtoken": reqtoken
    }
 
    result = requests.post(url=url, data=json.dumps(data), headers=headers, verify=False)
    text = result.text
    text = text.split(',')[2]
    text = text.split(':')[1]
    if text == '100':
        text = '，满分！'
    print(account,text)
 
 
if __name__ == '__main__':
    # 加载题库数据
    with open('题库.txt','r') as f:
        question_data = f.read().split('\n')
        
    # 加载账号数据
    user_data_list = user_data_list_parse()


    # selenium设置与启动
    options = webdriver.EdgeOptions()
    prefs = {"profile.managed_default_content_settings.images": 2}
    options.add_experimental_option("prefs", prefs)
    driver = webdriver.Edge(service=EdgeService(EdgeChromiumDriverManager().install()), options=options)
    driver.get('https://www.2-class.com/competition')
    driver.maximize_window()

    
    # 计数
    count = 0
    # 开始运行答题
    try:
        for user_data in user_data_list:
            login(user_data)
            count = count + 1
            print('已完成'+ str(count) + '个' )
            if count%35 == 0:
                print('按照计划休眠30分钟')
                time.sleep(1800)
        print('全部完成')
    except Exception as e:
        wb = Workbook()
        ws = wb.active
        for i in user_data_list[count:]:
            ws.append(i)   
        wb.save('账户.xlsx')

        print('程序运行错误，已经保存数据\n')
        print(e)
    finally:
        driver.quit()   # 使用完, 关闭浏览器
